<template>
  <div class="card" style="display: flex">
    <div>
      <el-input style="width: 240px;" v-model="data.searchTitle" placeholder="请输入公告标题查询"
        prefix-icon="Search"></el-input>
      <el-button style="margin-left: 10px;" type="primary" @click="load()">查询</el-button>
      <el-button style="margin-left: 10px;" @click="reset()">重置</el-button>
    </div>
    <div style="margin-left: auto;">
      <el-button style="margin-left: 10px;" type="primary" @click="add()">上传</el-button>
      <el-button style="margin-left: 10px;" type="danger" @click="deleteall()">批量删除</el-button>
    </div>
  </div>

  <div class="card">
    <el-table :data="data.noticeList" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="公告标题" prop="title" />
      <el-table-column label="发布时间" prop="publishTime" />
      <el-table-column label="类型" prop="noticeType" :filters="[
                { text: '公告', value: '公告' },
                { text: '政策', value: '政策' },
            ]" :filter-method="filterHandler" />
    </el-table>
    <div style="margin-top: 15px;">
      <el-pagination v-model:current-page="data.pageNumber" v-model:page-size="data.pageSize"
        :page-sizes="[1, 5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="data.total"
        @size-change="load()" @current-change="load()" />
    </div>
  </div>

  <el-dialog title="添加公告" v-model="data.formVisable" width="500">
    <el-form :model="data.form" ref="formRef" :rules="data.rules" label-width="150px">
      <el-form-item label="公告标题 " prop="title">
        <el-input v-model="data.form.title"></el-input>
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker v-model="data.form.publishTime" placeholder="选择发布日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="内容" prop="contentHtml">
        <el-upload 
        :auto-upload="false" 
        :on-change="handleFileChange" 
        :limit="1" 
        :file-list="fileList" 
        accept=".docx"
        :before-upload="beforeUpload"
        :on-exceed="handleExceed"
        drag>
          <el-icon>
            <Upload />
          </el-icon>
          <div class="el-upload__text">
            拖拽或点击上传 <em>.docx</em> 文件
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="类型 " prop="noticeType">
        <el-select v-model="data.form.noticeType" placeholder="请选择公告类型">
          <el-option label="公告" value="公告"></el-option>
          <el-option label="政策" value="政策"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancle()">取消</el-button>
        <el-button type="primary" @click="handleConfirm()">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import request from '@/utils/request';
import { nextTick, reactive, ref } from 'vue';

const data = reactive({
  pageNumber: 1,
  pageSize: 5,
  total: 0,
  formVisable: false,
  rules: {
    title: [
      { required: true, message: '请输入公告标题', trigger: ['change', 'blur'] },
      { max: 50, message: '长度在50 个字符以内', trigger: ['change', 'blur'] }
    ],
    publishTime: [
      { required: true, message: '请输入发布时间', trigger: ['change', 'blur'] },
    ],
    noticeType: [
      { required: true, message: '请选择公告类型', trigger: ['change', 'blur'] },
    ]
  },
  form: {
    id: "",
    title: "",
    publishTime: "",
    contentHtml: "",
    noticeType: "",
  },
  notice: {//选中的行对象
    id: "",
    title: "",
    publishTime: "",
    contentHtml: "",
    noticeType: "",
  },
  noticeList: [],
  notices: [],//选中的行对象数组
  searchTitle: "",
})

const formRef = ref()
const file = ref()
const fileList = ref([])

const load = () => {//查询所有公告
  request.get('/notice/searchPage', {
    params: {
      pageNumber: data.pageNumber,
      pageSize: data.pageSize,
    }
  }).then(res => {
    data.noticeList = res.data.list
    data.total = res.data.total
  })
}
load()

const handleSelectionChange = (row) => {//选中的行对象
  data.notice = row
}

const resetform = () => {//重置表单
  data.form = {
    id: "",
    title: "",
    publishTime: "",
    contentHtml: "",
    noticeType: "",
  }
  nextTick(() => {
    formRef.value.clearValidate(); // 清除表单验证状态
    formRef.value.resetFields(); // 重置表单
  })
}
const add = () => {//添加公告,打开弹窗
  data.formVisable = true
  resetform()
}
const filterHandler = (value,row,column) => {//根据公告类型过滤
  const property = column['property']
  return row[property] === value
}
/*************文件上传******************* */
const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB

const beforeUpload = (file) => {
  const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  const isLt5M = file.size <= MAX_FILE_SIZE
  if (!isDocx) {
    ElMessage.error('只能上传 .docx 格式的文件')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB')
    return false
  }
  return true // 允许上传
}
const handleFileChange = (uploadFile) => {
  file.value = uploadFile.raw
}
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件，请先移除原文件')
}
const handleUpload = () => {//上传公告
  const formData = new FormData()
  formData.append('title', data.form.title)
  formData.append('noticeType', data.form.noticeType)
  formData.append('publishTime', data.form.publishTime)
  formData.append('file', file.value)
  request.post('/notice/upload', formData).then(res => {
    if (res.code == 200) {
      ElMessage.success("上传成功")
      load()
    } else {
      ElMessage.error(res.message)
    }
  })
}

const handleCancle = () => {
  data.formVisable = false
  resetform()
}
const handleConfirm = () => {//修改或新增员工信息
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return false
    }
  })
  //根据员工编号判断是修改还是新增
  if (data.form.employeeId !== '' && data.form.employeeId !== undefined && data.form.employeeId !== null) {
    request.post('/notice/update', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('修改成功')
        load()
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
  else {
    handleUpload()
  }
  data.formVisable = false
}

const deleteall = () => {//批量删除
  if (data.notices.length === 0) {
    ElMessage.warning("请选择数据")
    return
  }
  ElMessageBox.confirm('删除数据后无法恢复，确认删除？', { type: 'warning' }).then(() => {
    request.post("/notice/deletebatch", data.notices).then(res => {
      if (res.code = '200') {
        ElMessage.success("删除成功")
        load()
      }
      else {
        ElMessage.error(res.message)
      }
    })
  })
}
const reset = () => {
  data.searchTitle = ''
  load()
}

</script>

<style scoped>

</style>